package com.base.cn.platform.os.controller.web.course.user;

import com.base.cn.platform.os.common.WebBaseController;
import com.base.cn.platform.os.common.j2cache.CustomCacheChannel;
import com.base.cn.platform.os.common.j2cache.J2CacheRegion;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.order.OrderStatus;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.entity.user.user.UserCondition;
import com.base.cn.platform.os.service.course.catalog.CourseCatalogService;
import com.base.cn.platform.os.service.course.classes.ClassesService;
import com.base.cn.platform.os.service.course.cou.buy.CourseBuyRecordService;
import com.base.cn.platform.os.service.course.cou.record.CoursePlayRecordService;
import com.base.cn.platform.os.service.exam.extend.ExamUserExpandService;
import com.base.cn.platform.os.service.manage.user.user.CusUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 个人中心课程页面
 *
 * @author ll
 * @date 2018/5/23 8:51
 */
@Controller
@RequestMapping("/web/uc/course")
public class WebUserCourseController extends WebBaseController {

    @Autowired
    private CourseBuyRecordService courseBuyRecordService;
    @Autowired
    private CourseCatalogService courseCatalogService;
    @Autowired
    private CoursePlayRecordService coursePlayRecordService;
    @Autowired
    private ClassesService classesService;
    @Autowired
    private ExamUserExpandService examUserExpandService;
    @Autowired
    private CusUserService cusUserService;
    @Autowired
    private CustomCacheChannel customCacheChannel;

    /**
     * 我的课程
     *
     * @param model
     * @return
     */
    @RequestMapping("/user/index")
    public String myCourse(Model model, HttpServletRequest request) {
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        UserCondition condition = new UserCondition();
        condition.setId(userId);
        condition.setNotStudy(true);
        Map<String, Object> userStudy = cusUserService.userStudyInfo(condition);
        model.addAttribute("userStudy", userStudy);
        return resultPage("/course/user/u-index");
    }

    /**
     * 获取用户课程数据
     *
     * @return Map<String   ,   Object>
     */
    @RequestMapping("/getUserCourseNum")
    @ResponseBody
    public Map<String, Object> getUserCourseNum(HttpServletRequest request) {
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        Map<String, Integer> userCountNum = courseBuyRecordService.getUserCourseNum(userId);
        return ResultUtil.SUCCESS(userCountNum);
    }

    /**
     * 获取用户最后播放的目录
     *
     * @param request
     * @return
     */
    @RequestMapping("/getUserLastStudyCourseCatalog")
    @ResponseBody
    public Map<String, Object> getUserLastStudyCourseCatalog(HttpServletRequest request) {
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        Map<String, Object> coursePlayRecord = coursePlayRecordService.getUserLastPlayCourseRecord(userId);
        return ResultUtil.SUCCESS(coursePlayRecord);
    }

    /**
     * 基本学习统计
     *
     * @param request HttpServletRequest
     * @return Map<String   ,   Object>
     */
    @RequestMapping("/userStudyBaseStatistics")
    @ResponseBody
    public Map<String, Object> userStudyBaseStatistics(HttpServletRequest request) {
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        Map<String, Object> dataMap = new HashMap<>();
        Map<String, Object> examUserExpand = examUserExpandService.findExamUserExpandByUserId(userId);
        dataMap.put("examUserExpand", examUserExpand);
        Map<String, Object> user = cusUserService.userInfo(userId, false, false, false, false, false, false, false);
        user.remove("password");
        user.remove("customerkey");
        dataMap.put("user", user);
        return ResultUtil.SUCCESS(dataMap);
    }

    /**
     * 我的课程列表
     *
     * @param model
     * @return
     */
    @RequestMapping("/ajax/myCourseList")
    public String ajaxMyCourse(HttpServletRequest request,
                               Model model,
                               @RequestParam(value = "currentPage", required = false, defaultValue = "1") Integer currentPage,
                               @RequestBody Map<String, Object> params) {
        params.put("userId", webMobileLoginUtil.getLoginUserId(request));
        params.put("courseStatus", OrderStatus.SUCCESS);
        Map<String, Object> dataMap = courseBuyRecordService.findCourseBuyRecordFrontPage(params, currentPage, 10, true, false, false, true, false, false, true);
        model.addAttribute("dataMap", dataMap);
        return resultPage("/course/user/u-ajax-myCourse");
    }

    /**
     * 获取要激活的套餐下课程的数据
     *
     * @param recordId 购买记录
     * @return Map<String   ,   Object>
     */
    @RequestMapping("/getActivationPackage")
    @ResponseBody
    public Map<String, Object> getActivationPackage(HttpServletRequest request,
                                                    @RequestParam("recordId") BigDecimal recordId) {
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        return courseBuyRecordService.findPackageActivationById(recordId, userId);
    }

    /**
     * 执行激活套餐课程
     *
     * @param recordId  购买记录ID
     * @param courseIds 选择的课程ID
     * @return Map<String   ,   Object>
     */
    @RequestMapping("/activationPackage")
    @ResponseBody
    public Map<String, Object> activationPackage(HttpServletRequest request,
                                                 @RequestParam("recordId") BigDecimal recordId,
                                                 @RequestParam("courseIds") String courseIds) {
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        return courseBuyRecordService.activationPackage(userId, recordId, courseIds);
    }

    /**
     * 去课程详情页面
     *
     * @return
     */
    @RequestMapping("/info")
    public String queryMyCourseInfo(HttpServletRequest request,
                                    Model model,
                                    @RequestParam("recordId") BigDecimal recordId) {
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        Map<String, Object> courseBuyRecord = courseBuyRecordService.findCourseBuyRecordById(recordId, userId, true, true);
        model.addAttribute("courseBuyRecord", courseBuyRecord);
        return resultPage("/course/user/u-course-info");
    }

    /**
     * 查询课程目录
     *
     * @param model    model
     * @param courseId 课程ID
     */
    @RequestMapping("/queryCourseCatalog")
    public String queryCourseCatalog(Model model,
                                     HttpServletRequest request,
                                     @RequestParam("buyCourseId") BigDecimal buyCourseId,
                                     @RequestParam("courseId") BigDecimal courseId) {
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        List<Map<String, Object>> courseCatalogList = courseCatalogService.findCourseCatalogLayeredByCourseId(buyCourseId, userId, courseId, true, false, false, false, true);
        model.addAttribute("courseCatalogList", courseCatalogList);
        return resultPage("/course/user/u-course-directory");
    }

    /**
     * 获取用户的某个课程的学习统计数据
     *
     * @param request  HttpServletRequest
     * @param courseId 课程ID
     * @return Map<String   ,   Object>
     */
    @RequestMapping("/getUserStudyCountData")
    @ResponseBody
    public Map<String, Object> getUserStudyCountData(HttpServletRequest request,
                                                     @RequestParam("courseId") BigDecimal courseId) {
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        String keyName = "user_study_count_data_" + userId;
        Map<String, Object> timeMap = (Map<String, Object>) customCacheChannel.get(J2CacheRegion.THIRTY_MINUTE_REGION.getKey(), keyName);
        if (ObjectUtils.isEmpty(timeMap)) {
            timeMap = new HashMap<>();
            //课程的总学习时间（分）
            Integer studySumTime = coursePlayRecordService.queryUserStudySumTime(userId, courseId);
            if (studySumTime == null) {
                studySumTime = 0;
            }
            timeMap.put("studySumTime", studySumTime);
            //课程当前周的学习时间（分）
            Integer weekStudTime = coursePlayRecordService.queryUserWeekStudySumTime(userId, courseId);
            if (weekStudTime == null) {
                weekStudTime = 0;
            }
            timeMap.put("weekStudTime", weekStudTime);
            //查询用户对课程的学习的排行名次（根据学习时间进行排序）
            Integer studyCourseRank = coursePlayRecordService.queryUserStudyCourseRankings(userId, courseId);
            if (studyCourseRank == null) {
                studyCourseRank = 0;
            }
            timeMap.put("studyCourseRank", studyCourseRank);
            Map<String, Object> rankOneUser = coursePlayRecordService.queryUserStudyCourseRankOneUser(courseId);
            timeMap.put("rankOneUser", rankOneUser);
            customCacheChannel.set(J2CacheRegion.THIRTY_MINUTE_REGION.getKey(), keyName, timeMap);//缓存30分钟
        }
        return ResultUtil.SUCCESS(timeMap);
    }

    /**
     * 获取课程下的班级列表
     *
     * @param courseId 课程ID
     * @return Map<String   ,   Object>
     */
    @RequestMapping("/getCourseToClass")
    @ResponseBody
    public Map<String, Object> getCourseToClass(@RequestParam("courseId") BigDecimal courseId) {
        List<Map<String, Object>> classesList = classesService.findCourseToClassesList(courseId);
        return ResultUtil.SUCCESS(classesList);
    }
}
